package com.note.app.handler;

import com.note.common.exception.BusinessException;
import com.note.common.vo.ResponseVo;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.Iterator;
import java.util.Set;

/**
 * 全局异常处理器
 * 统一处理所有控制器抛出的异常，返回统一格式的响应
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     * 
     * @param e 业务异常
     * @return 统一格式的响应
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseVo<Void> handleBusinessException(BusinessException e) {
        log.warn("业务异常: {}", e.getMessage());
        return ResponseVo.error(e.getCode(), e.getMessage());
    }
    
    /**
     * 处理404资源不存在异常
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseVo<Void> handleNoHandlerFoundException(NoHandlerFoundException e) {
        String requestURL = e.getRequestURL();
        log.warn("请求的资源不存在: {} {}", e.getHttpMethod(), requestURL);
        return ResponseVo.error(HttpStatus.NOT_FOUND.value(), 
                String.format("资源不存在: %s - 请检查请求地址是否正确", requestURL));
    }
    
    /**
     * 处理参数校验异常
     * 
     * @param e 参数校验异常
     * @return 统一格式的响应
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseVo<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.warn("参数校验不通过: {}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getDefaultMessage()).append("; ");
        }
        return ResponseVo.paramError(sb.toString());
    }

    /**
     * 处理参数绑定异常
     * 
     * @param e 参数绑定异常
     * @return 统一格式的响应
     */
    @ExceptionHandler(BindException.class)
    public ResponseVo<Void> handleBindException(BindException e) {
        log.warn("参数绑定异常: {}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getDefaultMessage()).append("; ");
        }
        return ResponseVo.paramError(sb.toString());
    }

    /**
     * 处理约束违反异常
     * 
     * @param e 约束违反异常
     * @return 统一格式的响应
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseVo<Void> handleConstraintViolationException(ConstraintViolationException e) {
        log.warn("参数约束违反异常: {}", e.getMessage());
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        StringBuilder sb = new StringBuilder();
        Iterator<ConstraintViolation<?>> iterator = violations.iterator();
        while (iterator.hasNext()) {
            ConstraintViolation<?> violation = iterator.next();
            sb.append(violation.getMessage());
            if (iterator.hasNext()) {
                sb.append("; ");
            }
        }
        return ResponseVo.paramError(sb.toString());
    }

    /**
     * 处理请求体解析异常
     * 
     * @param e 请求体解析异常
     * @return 统一格式的响应
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseVo<Void> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.warn("请求体解析异常: {}", e.getMessage());
        return ResponseVo.paramError("请求体格式错误");
    }

    /**
     * 处理请求参数缺失异常
     * 
     * @param e 请求参数缺失异常
     * @return 统一格式的响应
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseVo<Void> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.warn("请求参数缺失: {}", e.getMessage());
        return ResponseVo.paramError("参数" + e.getParameterName() + "不能为空");
    }

    /**
     * 处理请求方法不支持异常
     * 
     * @param e 请求方法不支持异常
     * @return 统一格式的响应
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public ResponseVo<Void> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.warn("请求方法不支持: {}", e.getMessage());
        return ResponseVo.error(HttpStatus.METHOD_NOT_ALLOWED.value(), 
                "不支持" + e.getMethod() + "请求方法，支持的方法: " + String.join(", ", e.getSupportedMethods()));
    }

    /**
     * 处理参数类型不匹配异常
     * 
     * @param e 参数类型不匹配异常
     * @return 统一格式的响应
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseVo<Void> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        log.warn("参数类型不匹配: {}", e.getMessage());
        return ResponseVo.paramError("参数'" + e.getName() + "'类型错误，应为" + e.getRequiredType().getSimpleName() + "类型");
    }

    /**
     * 处理MongoDB ID转换异常
     * 
     * @param e 异常
     * @return 统一格式的响应
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseVo<Void> handleIllegalArgumentException(IllegalArgumentException e) {
        if (e.getMessage() != null && e.getMessage().contains("ObjectId")) {
            log.warn("MongoDB ID格式不正确: {}", e.getMessage());
            return ResponseVo.paramError("ID格式不正确，MongoDB ID应为24个字符的十六进制字符串");
        }
        log.warn("参数不合法: {}", e.getMessage());
        return ResponseVo.paramError(e.getMessage());
    }

    /**
     * 处理所有未捕获的异常
     * 
     * @param e 异常
     * @return 统一格式的响应
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseVo<Void> handleException(Exception e) {
        log.error("未知异常: ", e);
        return ResponseVo.error("服务器内部错误，请稍后再试");
    }

} 